package com.zll.dms.utils;

import com.zll.dms.exception.MyBaseException;
import com.zll.dms.mapper.UserMapper;
import com.zll.dms.model.User;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;

import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 通用工具类
 */
public class CommonUtils {

    /**
     * 验证邮箱格式
     * @param email
     * @return
     */
    public static boolean checkEMail(String email) {
        if (StringUtils.isBlank(email)) {
            return false;
        }
        boolean flag = false;
        try {
            String check = "^[\\S]+@[\\S]+.[\\S]+$";
            Pattern pattern = Pattern.compile(check);
            Matcher matcher = pattern.matcher(email);
            flag = matcher.matches();
        } catch (Exception e) {
            flag = false;
        }
        return flag;
    }

    /**
     * 获取当前登录用户id
     * @return
     */
    public static Long getCurrentUserId(UserMapper userMapper) {
        return getCurrentUser(userMapper).getId();
    }


    /**
     * 获取当前登录用户
     * @return
     */
    public static User getCurrentUser(UserMapper userMapper) {
        Subject subject = SecurityUtils.getSubject();
        String userName = subject.getPrincipal().toString();
        List<User> users = userMapper.getUserByName(userName);
        if (CollectionUtils.isEmpty(users)) {
            throw new MyBaseException("未找到当前登录用户");
        }
        User user = users.get(0);
        return user;
    }

}
